﻿/* ==============================================================================
 * 功能描述：SubPool  
 * 
 * 创 建 者：郑镇泉
 * 
 * 创建日期：2016/4/4 19:17:57
 * ==============================================================================*/
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.Security.Principal;

public class SubPool
{
    /// <summary>
    /// 对象池拥有的物体集合
    /// </summary>
    private List<GameObject> objectList = null;

    /// <summary>
    /// 对象池拥有的物体的原始预设体
    /// </summary>
    private GameObject prefab;

    /// <summary>
    /// 对象池拥有的物体的父物体
    /// </summary>
    private Transform parent;

    public SubPool(GameObject pr, Transform pa)
    {
        objectList = new List<GameObject>();
        prefab = pr;
        parent = pa;
    }

    /// <summary>
    /// 从对象池中取出一个物体
    /// </summary>
    /// <returns></returns>
    public GameObject Spawn()
    {
        GameObject go = null;
        foreach (GameObject gameObject in objectList)
        {
            if (gameObject.activeSelf == false)
            {
                go = gameObject;
            }
        }
        //Debug.Log("取出一个物品："+go);
        if (go == null)
        {
            go=CreatObject();
        }
        go.SetActive(true);
        go.GetComponent<IPool>().Spawn();
        return go;
    }

    /// <summary>
    /// 把一个物体放入对象池中
    /// </summary>
    /// <param name="obj"></param>
    public void UnSpawn(GameObject obj)
    {
        if (objectList.Contains(obj))
        {
            obj.GetComponent<IPool>().UnSpawn();
            obj.transform.SetParent(parent,false);
            obj.SetActive(false);
        }
    }

    /// <summary>
    /// 把所有属于该对象池的物体都回收
    /// </summary>
    public void UnSpawnAll()
    {
        foreach (GameObject gameObject in objectList)
        {
            gameObject.GetComponent<IPool>().UnSpawn();
            gameObject.transform.SetParent(parent, false);
            gameObject.SetActive(false);
        }
    }

    /// <summary>
    /// 创建一个新的物体
    /// </summary>
    private GameObject CreatObject()
    {
        GameObject go = UnityEngine.GameObject.Instantiate(prefab);
        go.SetActive(false);
        objectList.Add(go);
        return go;
    }

    /// <summary>
    /// 对象池中是否存在某个物体
    /// </summary>
    /// <param name="obj"></param>
    /// <returns></returns>
    public bool HasObject(GameObject obj)
    {
        if (objectList.Contains(obj)) return true;
        return false;
    }
}